package com.longcai.piaojia.activity;

import android.Manifest;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.longcai.piaojia.R;
import com.longcai.piaojia.conn.GoodsInfoGet;
import com.longcai.piaojia.util.AMapUtil;
import com.longcai.piaojia.util.DriveRouteColorfulOverLay;
import com.longcai.piaojia.util.UtilPermission;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.util.UtilToast;

/**
 * Created by Administrator on 2016/9/9.
 */
public class MapActivity extends BaseActivity implements AMap.OnMapClickListener, View.OnClickListener,
        AMap.OnMarkerClickListener, AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter, AMap.OnMapLoadedListener, LocationSource, AMapLocationListener, RouteSearch.OnRouteSearchListener {

    @BoundView(R.id.map_title_tv) private TextView map_title_tv;
    @BoundView(R.id.map_mv) private MapView map_mv;
    @BoundView(R.id.map_arrow_rl) private RelativeLayout map_arrow_rl;
    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private RouteSearch mRouteSearch;
    private LatLonPoint showPoint;
    private LatLonPoint minePoint;
    private DriveRouteResult mDriveRouteResult;
    private GoodsInfoGet.GoodsInfoEntity goodsInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] permission = {Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS};

        UtilPermission.Permission(this, permission);

        setContentView(R.layout.activity_map);

        goodsInfo = (GoodsInfoGet.GoodsInfoEntity) getIntent().getSerializableExtra("goodsInfo");

        showPoint = new LatLonPoint(goodsInfo.place_lat, goodsInfo.place_lng);

        setBackTrue();

        map_title_tv.setText(goodsInfo.title);

        map_mv.onCreate(savedInstanceState);// 此方法必须重写

        if (aMap == null) {
            aMap = map_mv.getMap();
//            MyLocationStyle myLocationStyle = new MyLocationStyle();
//            myLocationStyle.myLocationIcon(BitmapDescriptorFactory
//                    .fromResource(R.mipmap.point1));// 设置小蓝点的图标
//
//            myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
//            myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
//
//            // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
//            myLocationStyle.strokeWidth(0.1f);// 设置圆形的边框粗细
//            aMap.setMyLocationStyle(myLocationStyle);
//            aMap.setMyLocationRotateAngle(180);

            aMap.setLocationSource(this);// 设置定位监听
            aMap.setOnMapLoadedListener(this);
            aMap.setOnMapClickListener(this);
            aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
            aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
            aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式

            aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
            aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
            aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

            aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
            //将地图移动到定位点
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(showPoint.getLatitude(), showPoint.getLongitude())));

            mRouteSearch = new RouteSearch(this);
            mRouteSearch.setRouteSearchListener(this);

        }

        map_arrow_rl.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.map_arrow_rl:

                if(minePoint.getLatitude()!=0&&minePoint.getLongitude()!=0){

                    aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
                    //将地图移动到定位点
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(minePoint.getLatitude(), minePoint.getLongitude())));

                }

                break;

        }

    }

    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(int routeType, int mode) {
        if (minePoint == null) {
            UtilToast.show(MapActivity.this, getString(R.string.map_not_set_start_text));
            return;
        }
        if (showPoint == null) {
            UtilToast.show(MapActivity.this, getString(R.string.map_not_set_end_text));
        }
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                minePoint, showPoint);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, mode, null,
                null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        map_mv.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        map_mv.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map_mv.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (map_mv != null) {

            map_mv.onDestroy();

        }

        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {

        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
//                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
//                float bearing = aMap.getCameraPosition().bearing;
//                aMap.setMyLocationRotateAngle(bearing);// 设置小蓝点旋转角度
                minePoint = new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude());

                searchRouteResult(2, RouteSearch.DrivingDefault);

                Log.v("maning", amapLocation.getAddress() + amapLocation.getAoiName() + amapLocation.getDistrict());
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.v("maning", errText);
            }
        }

    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setOnceLocation(true);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {

        aMap.clear();// 清理地图上的所有覆盖物
        if (errorCode == 1000) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mDriveRouteResult = result;
                    final DrivePath drivePath = mDriveRouteResult.getPaths()
                            .get(0);
                    DriveRouteColorfulOverLay drivingRouteOverlay = new DriveRouteColorfulOverLay(
                            aMap, drivePath,
                            mDriveRouteResult.getStartPos(),
                            mDriveRouteResult.getTargetPos(), null);
                    drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                    drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap();
                    drivingRouteOverlay.zoomToSpan();
                    int dis = (int) drivePath.getDistance();
                    int dur = (int) drivePath.getDuration();
                    String des = AMapUtil.getFriendlyTime(dur)+"("+AMapUtil.getFriendlyLength(dis)+")";

                    Log.v("maning", des);

//                    mRotueTimeDes.setText(des);
//                    mRouteDetailDes.setVisibility(View.VISIBLE);
                    int taxiCost = (int) mDriveRouteResult.getTaxiCost();
                    Log.v("maning", "打车约"+taxiCost+"元");
//                    mRouteDetailDes.setText("打车约"+taxiCost+"元");
//                    mBottomLayout.setOnClickListener(new OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            Intent intent = new Intent(mContext,
//                                    DriveRouteDetailActivity.class);
//                            intent.putExtra("drive_path", drivePath);
//                            intent.putExtra("drive_result",
//                                    mDriveRouteResult);
//                            startActivity(intent);
//                        }
//                    });
                } else if (result != null && result.getPaths() == null) {
//                    ToastUtil.show(mContext, R.string.no_result);
                }

            } else {
//                ToastUtil.show(mContext, R.string.no_result);
            }
        } else {
//            UtilToast.show(this.getApplicationContext(), "无");
        }

    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onMapLoaded() {



    }

    @Override
    public View getInfoWindow(Marker marker) {

        View view = null;

        if(view==null){

            view = getLayoutInflater().inflate(R.layout.activity_map_marker_no,
                    null);

        }

        return view;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

//    @Override
//    public void onInfoWindowClick(Marker marker) {
//
//
//    }
//
//    @Override
//    public boolean onMarkerClick(Marker marker) {
//
////        marker.showInfoWindow();
//
//        return false;
//    }
//
//    @Override
//    public View getInfoWindow(Marker marker) {
//
//        View infoWindow = null;
//
//        if (infoWindow == null) {
//
//            infoWindow = ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) getLayoutInflater().inflate(
//                    R.layout.activity_map_infowindow, null));
//
//        }
//
//        return infoWindow;
//
//    }
//
//    @Override
//    public View getInfoContents(Marker marker) {
//
//        return null;
//
//    }
//
//    @Override
//    public void onMapLoaded() {
//
//        aMap.getMapScreenMarkers().get(0).showInfoWindow();
//
//    }
}
